package logic

import (
	"context"
	"encoding/json"
	"newgoods/models/cache"
	"newgoods/models/mysql"
	"time"

	"newgoods/goodsrpc/goodsrpc"
	"newgoods/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询
func (l *GoodsListLogic) GoodsList(in *goodsrpc.GoodsListRequest) (*goodsrpc.GoodsListResponse, error) {
	// todo: add your logic here and delete this line
	/*
	   	SELECT
	        goods.id as goods_id,
	        goods.`name` as goods_name,
	        goods.price,
	        goods.stock,
	        goods.image,
	        classes.`name` as class_name,
	        goods.created_at
	      FROM
	        goods
	        LEFT JOIN classes ON goods.class_id = classes.id
	*/
	var goodsLists []*goodsrpc.GoodsList
	key := "list"

	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		goodsLists = mysql.GoodsList(mysql.DB)
		marshal, _ := json.Marshal(goodsLists)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &goodsLists)
	}

	return &goodsrpc.GoodsListResponse{
		List: goodsLists,
	}, nil
}
